﻿using com.iot.core.boot;
using com.iot.core.data;
using com.iot.core.data.entity;
using com.iot.core.data.service;
using com.iot.core.exception;
using com.iot.core.infrastructure;
using com.iot.core.manager.id;
using com.iot.ht.Controllers.htmenu.data;
using com.iot.ht.Controllers.htuser.data;
using Icom.iot.core.ext;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace com.iot.ht.Controllers.htmenu.service
{
    public class HtMenuService : BaseService<HtMenu>, IHtMenuService
    {
        readonly IRepository<HtPage> htPageMapper;
        readonly IRepository<HtPageAuth> htPageAuthMapper;
        public HtMenuService(IRepository<HtPage> p1,
            IRepository<HtPageAuth> p2
            ) 
        {
            htPageMapper = p1;
            htPageAuthMapper = p2;
        }

        public HtMenuDto InsertInit(HtMenuInsertQto qm)
        {
            var mm = new HtMenuDto
            {
                Id=HtIdManager.Current.NextLong(),
                Pid=qm.Id,
                HtplatId=qm.HtplatId,
                Lx=qm.Lx,
                Imgurl= "layui-icon-spread-left",
                Sortno=10

            };
             
            var Sortno = BaseMapper.GetAll().Where(a=>a.HtplatId==qm.HtplatId
                &&a.Pid==mm.Pid
            ) 
            .Max(a => (long?)a.Sortno)
            ;
            if (Sortno.HasValue)
            {
                mm.Sortno = Sortno.Value + 10;
            }
              
            return mm;
        }

        public async Task<HtMenuDto> DetailAsync(BaseQto qm)
        {
            var m = await BaseMapper.GetByIdAsync(qm.Id);
            var mm = new HtMenuDto();

            BaseMapper.EntityToDto(m, mm);
            if (m.HtpageId > 0)
            {
                var mpage = htPageMapper.GetById(m.HtpageId );
                mm.Code = mpage.Code;
                mm.P1 = mpage.P1;
                mm.P2 = mpage.P2;
                mm.P3 = mpage.P3;
                mm.P4 = mpage.P4;
                 
            }

            return mm;
        }
        public int Insert(HtMenuDto mm)
        {
            var m = new HtMenu();
            BaseMapper.DtoToEntity(mm, m);

            return Insert(m);
        }
        public int Update(HtMenuDto mm)
        {
            var m = GetById(mm.Id);
            BaseMapper.DtoToEntity(mm, m);
            return Update(m);
        }

    }
}
